package com.bs.visitservice.controller.seller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bs.visitservice.entity.Seller;
import com.bs.visitservice.entity.SellerDiscount;
import com.bs.visitservice.service.DiscountCouponService;
import com.bs.visitservice.service.SellerDiscountService;
import com.bs.visitservice.service.SellerService;
import com.bs.visitservice.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 店铺信息管理
 */
@RestController
@RequestMapping("/seller")
public class SellerInfoController {

    @Autowired
    private SellerService sellerService;
    @Autowired
    private DiscountCouponService discountCouponService;
    @Autowired
    private SellerDiscountService sellerDiscountService;

    /**
     * 删除店铺信息
     * @param cond
     * @return
     */
    @RequestMapping(value = "/removeSellerInfo",method = RequestMethod.POST)
    public Result removeSellerInfo(@RequestBody Map cond){
        Long sellerNo = Long.valueOf(String.valueOf(cond.get("sellerNo")));
        Long sellerLoginNo = (Long)ThreadLocalUtil.get("loginNo");
        LambdaQueryWrapper<Seller> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Seller::getLoginNo,sellerLoginNo).eq(Seller::getSellerNo,sellerNo);
        List<Seller> list = sellerService.list(wrapper);
        if(list.size()<1){
            return Result.error(null);
        }
        Seller seller = list.get(0);
        seller.setStatus(4);
        boolean isSuc = sellerService.updateById(seller);
        if(isSuc){
            return Result.success(null);
        }
        return Result.error(null);

    }
    /**
     * 店铺关闭
     * @param cond
     * @return
     */
    @RequestMapping(value = "/closeSellerInfo",method = RequestMethod.POST)
    public Result closeSellerInfo(@RequestBody Map cond){
        Long sellerNo = Long.valueOf(String.valueOf(cond.get("sellerNo")));
        Long sellerLoginNo = (Long)ThreadLocalUtil.get("loginNo");
        LambdaQueryWrapper<Seller> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Seller::getLoginNo,sellerLoginNo).eq(Seller::getSellerNo,sellerNo);
        List<Seller> list = sellerService.list(wrapper);
        if(list.size()<1){
            return Result.error(null);
        }
        Seller seller = list.get(0);
        seller.setStatus(3);
        boolean isSuc = sellerService.updateById(seller);
        if(isSuc){
            return Result.success(null);
        }
        return Result.error(null);

    }

    /**
     * 开店
     * @param cond
     * @return
     */
    @RequestMapping(value = "/openSellerInfo",method = RequestMethod.POST)
    public Result openSellerInfo(@RequestBody Map cond){
        Long sellerNo = Long.valueOf(String.valueOf(cond.get("sellerNo")));
        Long sellerLoginNo = (Long)ThreadLocalUtil.get("loginNo");
        LambdaQueryWrapper<Seller> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Seller::getLoginNo,sellerLoginNo).eq(Seller::getSellerNo,sellerNo);
        List<Seller> list = sellerService.list(wrapper);
        if(list.size()<1){
            return Result.error(null);
        }
        Seller seller = list.get(0);
        seller.setStatus(1);
        boolean isSuc = sellerService.updateById(seller);
        if(isSuc){
            return Result.success(null);
        }
        return Result.error(null);

    }
    /**
     * 查看商家店铺信息,排除已删除记录 status:4
     * @param cond
     * @return
     */
    @RequestMapping(value = "/querySellerInfo",method = RequestMethod.POST)
    public Result querySellerInfo(@RequestBody Map cond){
        IPage page = ParamUtils.getPage(cond);
        Long sellerLoginNo = (Long)ThreadLocalUtil.get("loginNo");
        LambdaQueryWrapper<Seller> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Seller::getLoginNo,sellerLoginNo).ne(Seller::getStatus,4);
        Map<String,Object> result = new HashMap<>();
        page = sellerService.pageMaps(page,wrapper);
        List<Map<String,Object>> records = page.getRecords();
        ResultUtil.transfort(records,getDictMap(),true);
        result.put("total",page.getTotal());
        result.put("datas",records);
        return Result.success(result);
    }


    /**
     * 获取列和字典值的映射关系
     * @return
     */
    private Map getDictMap(){
        Map<String,String> dictMap = new HashMap<>();
        dictMap.put("status","sellerStatus");
        dictMap.put("serveType","serveType");
        dictMap.put("type","discountType");
        return dictMap;
    }

    /**
     * 更新店铺信息
     * @return
     */
    @RequestMapping(value = "/updateSellerInfo",method = RequestMethod.POST)
    public Result updateSellerInfo(HttpServletRequest request){
        boolean isSuc = false;
        InputStream is = null;
        try {
            request.setCharacterEncoding("utf-8"); //设置编码
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            //获取formdata的值
            Iterator<String> iterator = req.getFileNames();
            Map<String, String[]> parameterMap = req.getParameterMap();
            Map<String,Object> transMap = new HashMap<>();
            parameterMap.forEach((k,v)->{
                transMap.put(k,v[0]);
            });
            Seller seller = (Seller)ResultUtil.transObject(transMap, Seller.class);
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                is = file.getInputStream();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] bytes = new byte[2048];
                int len = 0;
                while ((len = is.read(bytes))>0){
                    bos.write(bytes, 0,len);
                }
                byte[] res = bos.toByteArray();
                seller.setPhoto(res);
            }
            isSuc = sellerService.updateById(seller);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(isSuc){
            return Result.success(null);
        }
        return Result.error(null);

    }


    /**
     * 新增店铺信息,状态0 审核中
     * @param
     * @return
     */
    @RequestMapping("/saveSellerInfo")
    public Result saveSellerInfo(HttpServletRequest request){
        boolean isSuc = false;
        InputStream is = null;
        try {
            request.setCharacterEncoding("utf-8"); //设置编码
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            //获取formdata的值
            Iterator<String> iterator = req.getFileNames();
            Map<String, String[]> parameterMap = req.getParameterMap();
            Map<String,Object> transMap = new HashMap<>();
            parameterMap.forEach((k,v)->{
                transMap.put(k,v[0]);
            });
            Long loginNo = (Long)ThreadLocalUtil.get("loginNo");
            Seller seller = (Seller)ResultUtil.transObject(transMap, Seller.class);
            seller.setCreditPoint(100);
            seller.setRegistDate(new Date());
            seller.setStatus(0);
            seller.setLoginNo(loginNo);
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                is = file.getInputStream();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] bytes = new byte[2048];
                int len = 0;
                while ((len = is.read(bytes))>0){
                    bos.write(bytes, 0,len);
                }
                byte[] res = bos.toByteArray();
                seller.setPhoto(res);
            }
            isSuc = sellerService.save(seller);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(isSuc){
            return Result.success(null);
        }
        return Result.error(null);
    }

    /**
     * 查询所有商家优惠券
     * @param cond
     * @return
     */
    @RequestMapping(value = "/queryDisCount",method = RequestMethod.POST)
    public Result queryDisCount(@RequestBody Map cond){
        if(cond.get("pageIndex")!=null && cond.get("pageSize")!=null){
            Integer pageIndex = (Integer)cond.get("pageIndex");
            Integer pageSize = (Integer)cond.get("pageSize");
            cond.put("pageIndex",(pageIndex-1)*pageSize);
        }
        List<Map<String, Object>> maps = discountCouponService.querySellerDiscount(cond);
        ResultUtil.transfort(maps,this.getDictMap(),true);
        Integer total = discountCouponService.querySellerDiscount( null).size();
        Map<String,Object> result = new HashMap<>();
        result.put("datas",maps);
        result.put("total",total);
        return Result.success(result);
    }

    /**
     * 添加商家可用优惠券
     * @param cond
     * @return
     */
    @RequestMapping(value = "/saveSellerDiscount",method = RequestMethod.POST)
    public Result saveSellerDiscount(@RequestBody Map cond){
        SellerDiscount sd = (SellerDiscount)ResultUtil.transObject(cond, SellerDiscount.class);
        boolean isSuc = sellerDiscountService.save(sd);
        if(isSuc){
            return Result.success(null);
        }
        return Result.error(null);
    }

    /**
     * 删除商家可用优惠券
     * @param cond
     * @return
     */
    @RequestMapping(value = "/removeSellerDiscount",method = RequestMethod.POST)
    public Result removeSellerDiscount(@RequestBody Map cond){
        SellerDiscount sd = (SellerDiscount)ResultUtil.transObject(cond, SellerDiscount.class);
        boolean isSuc = sellerDiscountService.removeById(sd.getNo());
        if(isSuc){
            return Result.success(null);
        }
        return Result.error(null);
    }


}
